package com.sdx.console.activity.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Collections;

import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.customer.entity.CustomerInfo;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.activity.entity.*;
import com.sdx.console.activity.service.*;
import com.sdx.console.activity.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * 奖品 接口
 */
@RequestMapping("/activity/activityPrize")
@Controller
public class ActivityPrizeController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(ActivityPrizeController.class);
    private static final String MODEL = "/activity/activityPrize";


    @Resource
	private ActivityPrizeService activityPrizeService;

    @Resource
    private ResCloudFileService resCloudFileService;
	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request,Integer actId) {
        view.addObject("actId",actId);
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("activity.activityPrize.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request,Integer actId) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request,actId);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("activity.activityPrize.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer prizeId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        ActivityPrize activityPrize = activityPrizeService.queryById(prizeId);
        view.addObject("activityPrize", activityPrize);
		setPageParam(view,request,activityPrize.getActId());
		try {
			view.addObject("activityPrizeJson", JacksonUtils.toJsonString(activityPrize,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("activity.activityPrize.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request,Integer actId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request,actId);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("activity.activityPrize.query")
    @ResponseBody
    public JsonResult<PageQuery> list(ActivityPrize condtion)
    {
        PageQuery page = condtion.getPageQuery();
        activityPrizeService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,ActivityPrize activityPrize,HttpServletRequest request,MultipartFile prizeImgFile
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/prize/"+dir+"/";
		String bucketName = "sdxcomm";

        if (!FileUtils.isEmptyFile(prizeImgFile)) {
            try
            {
                String prizeImgFileNamePair = FileUtils.upload(subPath,prizeImgFile);
                String prizeImgStoreFile = prizeImgFileNamePair.split("::")[0];
                prizeImgStoreFile = subPath+prizeImgStoreFile;
                AliOSSApi.uploadLocalFile(FileUtils.getRoot()+prizeImgStoreFile,bucketName,prizeImgStoreFile.substring(1));
                String prizeImgUrl = "https://sdxcomm."+ ConfigService.ossDomain+prizeImgStoreFile;
                activityPrize.setPrizeImg(prizeImgUrl);
                resCloudFileService.insertResFile(ResCloudFile.ALI,prizeImgStoreFile,prizeImgUrl,"a","老师工作照");
            }catch(Exception e) {
                e.printStackTrace();
                result.setCode(JsonReturnCode.IO_ERROR.getCode());
                result.setMsg(e.getMessage());
            }
        }
		
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			activityPrize.setCreatedBy(user.getId().intValue());
			activityPrize.setCreatedName(user.getName());
			activityPrize.setCreatedTime(new Date());
			activityPrizeService.save(activityPrize);
		} else {
			activityPrize.setUpdatedBy(user.getId().intValue());
			activityPrize.setUpdatedName(user.getName());
			activityPrize.setUpdatedTime(new Date());
			activityPrizeService.updateTemplate(activityPrize);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("activity.activityPrize.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)ActivityPrize activityPrize,HttpServletRequest request
            ,@RequestParam("prizeImgFile") MultipartFile prizeImgFile
		)
    {

        return save(true,activityPrize,request,prizeImgFile
		);
    }

    @PostMapping("/update.json")
    @Function("activity.activityPrize.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  ActivityPrize activityPrize,HttpServletRequest request
            ,@RequestParam("prizeImgFile") MultipartFile prizeImgFile
		) {
		return save(false,activityPrize,request,prizeImgFile
		);
    }


   
    @GetMapping("/view.json")
    @Function("activity.activityPrize.query")
    @ResponseBody
    public JsonResult<ActivityPrize>queryInfo(Integer prizeId) {
        ActivityPrize activityPrize = activityPrizeService.queryById( prizeId);
        return  JsonResult.success(activityPrize);
    }

    @PostMapping("/delete.json")
    @Function("activity.activityPrize.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        activityPrizeService.batchDelActivityPrize(idList);
        return JsonResult.success();
    }
    

}
